import {
  Body,
  Controller,
  Get,
  Inject,
  LoggerService,
  Patch,
  Post,
  Query,
  Param,
  Delete,
} from '@nestjs/common';
import { WorkService } from './work.service';
import { CreateWorkDto } from './dto/create-work.dto';
import {
  checkPermission,
  User,
  JwtUser,
} from '@/common/decorators/current-user.decorator';

// 列表查询条件
export interface IndexCondition {
  pageIndex?: number;
  pageSize?: number;
  select?: string | string[]; // list中展示哪些字段
  populate?: { path: string; select?: string } | null;
  customSort?: Record<string, any>; // 排序
  find?: Record<string, any>; // 查询条件
}

@Controller('works')
export class WorkController {
  constructor(
    private readonly workService: WorkService,
    @Inject('CustomLogger') private readonly logger: LoggerService,
  ) {}

  @Post()
  async createWrok(@Body() createWork: CreateWorkDto, @User() user: JwtUser) {
    return this.workService.createWork({
      ...createWork,
      user: user._id,
      author: user.username,
    });
  }

  @Get()
  async myList(@User() user: JwtUser, @Query() query) {
    const { pageIndex, pageSize, isTemplate, title } = query;
    const listCondition: IndexCondition = {
      ...(pageIndex && { pageIndex: parseInt(pageIndex) }),
      ...(pageSize && { pageSize: parseInt(pageSize) }),
      select: 'id author copiedCount coverImg desc title user isHot createdAt',
      populate: { path: 'user', select: 'username nickName picture' },
      find: {
        user: user._id,
        ...(title && { title: { $regex: title, $option: 'i' } }),
        ...(isTemplate && { isTemplate: !!parseInt(isTemplate) }),
      },
    };
    this.logger.log('查询作品列表', listCondition);
    return this.workService.getList(listCondition);
  }

  @Get('templates')
  async templateList(@User() user: JwtUser, @Query() query) {
    const { pageIndex, pageSize, title } = query;
    const listCondition: IndexCondition = {
      ...(pageIndex && { pageIndex: parseInt(pageIndex) }),
      ...(pageSize && { pageSize: parseInt(pageSize) }),
      select: 'id author copiedCount coverImg desc title user isHot createdAt',
      populate: { path: 'user', select: 'username nickName picture' },
      find: {
        ...(title && { title: { $regex: title, $option: 'i' } }),
        isTemplate: true,
        isPublic: true,
      },
    };
    this.logger.log('查询模板列表', listCondition);
    return this.workService.getList(listCondition);
  }

  @Patch(':id')
  @checkPermission('Work', 'workNoPermissonFail')
  async updateWork(@Param('id') id: string, @Body() body) {
    return this.workService.updateOneWork({
      workId: id,
      updateContation: body,
    });
  }

  @Delete(':id')
  @checkPermission('Work', 'workNoPermissonFail')
  async deleteWork(@Param('id') id: string) {
    return this.workService.deleteOneWork({
      workId: id,
    });
  }

  @Post('publish/:id')
  @checkPermission('Work', 'workNoPermissonFail', { action: 'publish' })
  async publishWork(@Param('id') id: string) {
    return this.workService.publishWork({
      workId: id,
    });
  }

  @Post('publish-template/:id')
  @checkPermission('Work', 'workNoPermissonFail')
  async publishTemplate(@Param('id') id: string) {
    return this.workService.publishTemplate({
      workId: id,
    });
  }
}

@Controller('channels')
export class ChannelController {
  constructor(
    private readonly workService: WorkService,
    @Inject('CustomLogger') private readonly logger: LoggerService,
  ) {}

  @Post('')
  @checkPermission(
    { casl: 'Channel', mongoose: 'Work' },
    'workNoPermissonFail',
    { value: { type: 'body', valueKey: 'workId' } },
  )
  async createChannel(@Body() body: { channelName: string; workId: string }) {
    console.log('createChannel', body);
    return this.workService.createChannel(body);
  }

  @Get('')
  @checkPermission(
    { casl: 'Channel', mongoose: 'Work' },
    'workNoPermissonFail',
    { key: 'uuid', value: { type: 'query', valueKey: 'workId' } },
  )
  async getWorkChannel(@Query() query: { workId: string }) {
    return this.workService.getWorkChannel({
      workId: query.workId,
    });
  }

  @Patch(':id')
  @checkPermission(
    { casl: 'Channel', mongoose: 'Work' },
    'workNoPermissonFail',
    { key: 'channels._id', value: { type: 'params', valueKey: 'id' } },
  )
  async updateChannelName(
    @Param('id') id: string,
    @Body() body: { channelName: string },
  ) {
    return this.workService.updateChannelName({
      channelId: id,
      channelName: body.channelName,
    });
  }

  @Delete(':id')
  @checkPermission(
    { casl: 'Channel', mongoose: 'Work' },
    'workNoPermissonFail',
    { key: 'channels._id' },
  )
  async deleteChannel(@Param('id') id: string) {
    return this.workService.deleteChannel({
      channelId: id,
    });
  }
}
